package com.hjw.weixun.upload.action;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.util.ServletContextAware;

import com.hjw.weixun.domain.Weixun;
import com.hjw.weixun.service.WeixunService;
import com.hjw.weixun.service.impl.WeixunServiceImpl;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport implements
		ServletContextAware {

	private static final long serialVersionUID = -5016873153441103539L;

	private File doc;
	private String fileName;
	private String contentType;

	private ServletContext context;

	private String path;

	private Weixun weixun;

	private WeixunService weixunService;

	public FileUploadAction() {
		weixunService = WeixunServiceImpl.getInstance();
	}

	/**
	 * 更新Weixun 账户 Logo
	 * 
	 * @return
	 * @throws Exception
	 */
	public String uploadWeixunLogo() throws Exception {

		if (null != weixun) {
			weixun.setLogo(upload());

			weixunService.updateWeixunLogo(weixun);

		}

		return SUCCESS;
	}

	private String upload() throws Exception {

		// 获取
		String targetDirectory = ServletActionContext.getServletContext()
				.getInitParameter("sampleImageFolder");
		String targetFileName = generateFileName(fileName);
		File target = new File(targetDirectory, targetFileName);

		FileUtils.copyFile(doc, target);

		return targetFileName;
	}

	private String generateFileName(String fileName) {
		DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		String formatDate = format.format(new Date());

		int random = new Random().nextInt(10000);

		int position = fileName.lastIndexOf(".");
		String extension = fileName.substring(position);

		return formatDate + random + extension;
	}

	public void setDoc(File file) {
		this.doc = file;
	}

	public void setDocFileName(String fileName) {
		this.fileName = fileName;
	}

	public void setDocContentType(String contentType) {
		this.contentType = contentType;
	}

	public void setServletContext(ServletContext context) {
		this.context = context;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public Weixun getWeixun() {
		return weixun;
	}

	public void setWeixun(Weixun weixun) {
		this.weixun = weixun;
	}

}
